package com.xinqi.modules.prepare.common.service.impl;

import com.xinqi.common.security.utils.UserHelp;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.modules.prepare.common.service.PrepareAuthService;
import com.xinqi.modules.prepare.prepare.domain.PrepareMemberEntity;
import com.xinqi.modules.prepare.prepare.enums.PrepareMemberPermissionEnum;
import com.xinqi.modules.prepare.prepare.enums.PrepareMemberRoleEnum;
import com.xinqi.modules.prepare.prepare.manager.PrepareMemberManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 备课区权限校验服务
 *
 * @author linkai
 * @date 2023/3/20
 */
@Service
@RequiredArgsConstructor
public class PrepareAuthServiceImpl implements PrepareAuthService {
    private final PrepareMemberManager prepareMemberManager;

    /**
     * 验证备课区成员权限
     *
     * @param prepareId  备课区ID
     * @param userId     用户ID
     * @param permission 权限ID
     * @return 是否有权限
     */
    @Override
    public boolean validate(Long prepareId, Long userId, PrepareMemberPermissionEnum permission) {
        CommonErrors.BAD_REQUEST.check(prepareId != null, "备课区权限验证，备课区ID不能为空");
        CommonErrors.BAD_REQUEST.check(userId != null, "备课区权限验证，用户ID不能为空");
        CommonErrors.BAD_REQUEST.check(permission != null, "备课区权限验证，权限不能为空");
        // 获取成员信息
        PrepareMemberEntity member = Optional.ofNullable(prepareMemberManager.findByPrepareIdAndUserId(prepareId, userId))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("备课区权限验证，成员不存在"));
        // 获取成员角色
        PrepareMemberRoleEnum role = member.getRole();
        // 校验角色权限
        return role.validate(permission);
    }

    /**
     * 校验备课区成员权限
     *
     * @param prepareId  备课区ID
     * @param userId     用户ID
     * @param permission 权限ID
     */
    @Override
    public void check(Long prepareId, Long userId, PrepareMemberPermissionEnum permission) {
        CommonErrors.BAD_REQUEST.check(validate(prepareId, userId, permission), "备课区权限验证，没有操作权限");
    }

    /**
     * 校验备课区成员权限
     *
     * @param prepareId  备课区ID
     * @param permission 权限ID
     */
    @Override
    public void check(Long prepareId, PrepareMemberPermissionEnum permission) {
        CommonErrors.BAD_REQUEST.check(validate(prepareId, UserHelp.userId(), permission), "备课区权限验证，没有操作权限");
    }
}
